package com.yuni.index.Controller;

import com.yuni.index.Service.EmailService;
import com.yuni.index.utils.RedisUtil;

import org.springframework.beans.factory.annotation.Autowired;
import javax.mail.MessagingException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class VerificationController {

    private final EmailService emailService;
    private final RedisUtil redisUtil;

    @Autowired
    public VerificationController(EmailService emailService, RedisUtil redisUtil) {
        this.emailService = emailService;
        this.redisUtil = redisUtil;
    }

    @PostMapping("/sendCode")
    public ResponseEntity<Map<String, Object>> sendCode(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String email = request.get("email");
            String code = emailService.generateCode();
            emailService.sendEmail(email, code);
            redisUtil.saveCode(email, code);
            response.put("success", true);
            response.put("message", "验证码已发送，请在5分钟内使用");
        } catch (MessagingException e) {
            response.put("success", false);
            response.put("message", "发送失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    @GetMapping("/verifyCode")
    public ResponseEntity<Map<String, Object>> verifyCode(@RequestParam String email, @RequestParam String code) {
        Map<String, Object> response = new HashMap<>();
        String savedCode = redisUtil.getCode(email);
        if (savedCode != null && savedCode.equals(code)) {
            response.put("success", true);
            response.put("message", "验证码验证成功");
        } else {
            response.put("success", false);
            response.put("message", "验证码无效或已过期");
        }
        return ResponseEntity.ok(response);
    }
}
